﻿using Api.Web.helper;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Api.Web.filter
{
    /// <summary>
    /// 前台页面如果缺少projectId参数，自动跳转到home/projectList
    /// </summary>
    public class CheckProjectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (NoCheckProjectAttribute.IsIgnore(filterContext))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            //如果没有选择projectId并且页面不是在home/projectlist就跳转到home/projectlist中让用户去选择
            if (Th.ProjectId <= 0 && !Th.IsInThisPage())
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
                {
                    {"controller","Home" },
                    {"action","ProjectList" },
                });
            }
            base.OnActionExecuting(filterContext);
        }
    }

    public class NoCheckProjectAttribute : Attribute
    {
        /// <summary>
        /// 是否不检查ProjectId参数，true表示不检查
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        public static bool IsIgnore(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoCheckProjectAttribute), true).Count() > 0 ||
                filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(NoCheckProjectAttribute), true).Count() > 0)
            {
                return true;
            }
            return false;
        }
    }

    /// <summary>
    /// 检验后台页面是否具有projectId参数，没有就跳转到~/admin/project/list中给用户去选择
    /// </summary>
    public class CheckAdminProjectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (NoCheckProjectAttribute.IsIgnore(filterContext))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            //如果没有选择projectId并且页面不是在home/projectlist就跳转到home/projectlist中让用户去选择
            if (Th.ProjectId <= 0 && !Th.IsInThisPage())
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
                {
                    { "area","Admin"},
                    {"controller","Project" },
                    {"action","List" },
                });
            }
        }
    }
}